# _*_ coding:utf-8 _*_
from auser.models import User
from movie.models import Comment, Review, Movie, Stamp
from django import template

register = template.Library()


# FIXME:模板系统的运行分为两步︰编译和渲染
# def get_comment(parser, token):
# 	try:
# 		tag_name, format_string = token.split_content()
# 	except ValueError:
# 		raise template.TemplateSyntaxError(
# 			"{0} tag requires a single argument" .format(token.contents.spllit()[0])
# 		)
# 	if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
# 		raise template.TemplateSyntaxError(
# 			"%r tag's argument should be in quotes" % tag_name
# 		)
# 	return CurrentCommentNode(format_string[1:-1])


# 编写自定义标记的第二步是定义具有render()方法的Node子类。
# 继续上面的例子，我们需要定义CurrentTimeNode：
# class CurrentCommentNode(template.Node):
# 	def __init__(self,user):
# 		self.user = template.Variable(user)
# 	def render(self, context):
# 		try:
# 			actual_user = self.user.resolve(context)
# 			return actual_user.username
# 		except template.VariableDoesNotExist:
# 			return ''

@register.simple_tag
def get_comments(user):
	u = User.objects.get(pk=1)
	comments = user.comment_set.order_by('-timestamp')
	c = Comment.objects.get(pk=1)
	mid = c.movie_id
	html = '<div class="list-group" style="margin-left:20px">'
	for comment in comments:
		div = '''<a href="/movie_info/{movie_id}#{com_id}" class="list-group-item">
				<h4 class="list-group-item-heading">{name} 评论了 {movie_name}</h4>
				<p class="list-group-item-text">{content}</p>
                </a>'''.format(movie_id=comment.movie_id,
		                       com_id=comment.id,
		                       name=comment.user_username.encode('utf8'),
		                       movie_name=comment.movie_name.encode('utf8'),
		                       content=comment.content.encode('utf8'))
		html += div
	return html + "</div>"


@register.assignment_tag
def stared_or_liked(user):
	user = User.objects.get(pk=user.id)
	reviewpraises = user.reviewpraise_set.all()
	actions = []
	for review in reviewpraises:
		all_action = {}
		rew = Review.objects.get(pk=review.review_id)
		all_action['content'] = rew
		all_action['action'] = "liked"
		actions.append(all_action)

	moviespraises = user.stamp_set.all()
	for movie in moviespraises:
		all_action = {}
		mov = Movie.objects.get(pk=movie.movie_id)
		all_action['content'] = mov
		all_action['action'] = 'stared'
		actions.append(all_action)
	return actions


@register.filter
def get_rating(user, movie):
	try:
		stamp = Stamp.objects.get(user_id=user, movie_id=movie)
	except:
		return None
	else:
		return stamp.rate
